//
//  OAuthViewController.swift
//  微博项目
//
//  Created by mac on 16/1/14.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    //想把 访客视图的根视图 由UIView  变成UIWebView
    //可以定义成一个属性，方便其他的地方使用
    
    let webView = UIWebView()
    
    //MARK :关闭页面
  @objc private func close() {
    
    //dismiss 页面
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    //自动填充账号
    func defaultAccount() {
    
        //获取用户信息
    let jsString = "document.getElementById('userId').value = '15670559257',document.getElementById('passwd').value = 'huangpan521'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    override func loadView() {
        //将根视图 替换为webView
        view = webView
        
        //设置代理
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置导航条
        setNavBar()
        
        //加载授权页面
        loadOAuthPage()
    }

   private func setNavBar(){
    
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "账号测试", style: .Plain, target: self, action: "defaultAccount")
    
    }
    
    //-----------加载授权页面
   private func loadOAuthPage(){
    
    //1.获取url 
    let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
    
    //可选的url 
    let url = NSURL(string: urlString)!
    
    //获取request 
    let request = NSURLRequest(URL: url)
    
    webView.loadRequest(request)
//    print("-------1")
//    print(request)
    
    }
}


extension OAuthViewController: UIWebViewDelegate{
    
    
    func webViewDidStartLoad(webView :UIWebView){
        
        //显示
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView : UIWebView){
        
        //隐藏
        SVProgressHUD.dismiss()
    }
    
    //非常重要的方法
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print("-------2")
//        print(request)
        
//        print("********",request.URL?.absoluteString)
        
        guard let urlString = request.URL?.absoluteString else {
        
            //无法获取Url 的字符串 就直接不加载网页
            return false
        }
        
        if urlString.containsString("code="){
//            print("-------")
        print(urlString)
            //将url 中参数获取到
            guard let query = request.URL?.query else{
            
            return false
            }
            
            let codeStr = "code="
            //将 query 转换NSString  
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
//            print("code,-------query",code,query)
            
            //调用 获取token 的方法
            loadAccessToken(code)
            
            return false
        }
        return true
    }
    
    private func loadAccessToken(code: String){
    
        //请求token 和用户信息
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if !isSuccess {
            
                print("用户登录失败")
                
                //HUD提示用户登录失败
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            
            //登录成功
            SVProgressHUD.showSuccessWithStatus("登录成功")
            //执行dissmiss 操作  
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                //通知是同步的还是异步的
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVC, object: "Welcome")
                
                print("come here")
            })
            
            //切换根视图
//            UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
        }
    
    }
    
}

